package net.tycmc.cty.ctyms.timejob.iems.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.tycmc.bulb.common.util.MapGetter;
import net.tycmc.bulb.common.util.StringUtil;
import net.tycmc.cty.ctyms.timejob.common.DateList;
import net.tycmc.cty.ctyms.timejob.common.NumberFormat;
import net.tycmc.cty.ctyms.timejob.common.SMSContentCfg;
import net.tycmc.cty.ctyms.timejob.iems.dao.SMSInfoDAO;
import net.tycmc.cty.ctyms.timejob.iems.dao.SensorAlarmDAO;

public class SensorAlarmService {
	private SensorAlarmDAO tSensorAlarmDAO;
	private SMSInfoDAO smsInfoDAO; 
	private boolean SMSSmoke; 
	private boolean SMSSmokeRem; 
	private boolean SMSTemp; 
	private boolean SMSTempRem;
	
	private List<String> promptList = null;
	
	//录入提示表SQL
	private List<String> insertPrompt = null;
	private List<Object[]> paramPrompt = null;
	private List<String> insertSMS = null;
	private List<Object[]> paramSMS = null;

	public void settSensorAlarmDAO(SensorAlarmDAO tSensorAlarmDAO) {
		this.tSensorAlarmDAO = tSensorAlarmDAO;
	}

	public void setSmsInfoDAO(SMSInfoDAO smsInfoDAO) {
		this.smsInfoDAO = smsInfoDAO;
	}

	public void statSensorAlarm() {
		//此次处理的传感器报警ID数组， 不含头含尾
		Map<String,Object> flagSensor = this.tSensorAlarmDAO.getEventIDDef();
		
		//当前是否支持发送传感器短信
		if(this.smsInfoDAO.getSmsSendList().contains("SMSAS_SMSSmokeAlarm")){
			this.SMSSmoke = true;
		}
		if(this.smsInfoDAO.getSmsSendList().contains("SMSAS_SMSSmokeRels")){
			this.SMSSmokeRem = true;
		}
		if(this.smsInfoDAO.getSmsSendList().contains("SMSAS_SMSTempAlarm")){
			this.SMSTemp = true;
		}
		if(this.smsInfoDAO.getSmsSendList().contains("SMSAS_SMSTempRels")){
			this.SMSTempRem = true;
		}
		
		if(this.SMSSmoke||this.SMSSmokeRem||this.SMSTemp||this.SMSTempRem){
			this.insertSMS = new ArrayList<String>();
			this.paramSMS = new ArrayList<Object[]>();
		}
		
		//此次处理的传感器报警具体信息
		List<Map<String,Object>> sourceList = this.tSensorAlarmDAO.queryNeedWorkSensorAlarm(flagSensor);
		//提示表中报警中 的传感器报警序列，
		this.getAlarmStateOfPrompt(this.tSensorAlarmDAO.queryPromptOfSensorAlarm());
		if(null!=sourceList&&!sourceList.isEmpty()){
			this.insertPrompt = new ArrayList<String>();
			this.paramPrompt = new ArrayList<Object[]>();
			//报警 此次需要处理的传感器报警信息
			Map<String,Object> map =  this.workSensorAlarm(sourceList,promptList);
			
			if(null!= this.insertPrompt && null!=this.paramPrompt &&!this.insertPrompt.isEmpty() &&this.insertPrompt.size() == this.paramPrompt.size()){
				this.tSensorAlarmDAO.batchSumbitSQL(this.insertPrompt,this.paramPrompt);
			}
			if(null!= this.insertSMS && null!=this.paramSMS &&!this.insertSMS.isEmpty() && this.insertSMS.size() == this.paramSMS.size()){
				this.tSensorAlarmDAO.batchSumbitSQL(this.insertSMS,this.paramSMS);
			}
			this.tSensorAlarmDAO.updateFlagOfSensor(map);
		}
	}

	/**
	 * 录入提示表、发送短信
	 **/
	private Map<String,Object> workSensorAlarm(List<Map<String, Object>> sourceList,
			List<String> promptList) {
		Map<String,Object> reMap = new HashMap<String,Object>();
		String VehicleID = "";
		String MsgAlmC_SysA_ID = "";//传感器类型,17 温度；18烟度
		String statFlag = "";
		String userSMS = "";
		List<Map<String,Object>> userList = null;
		/*wangkai20141016新增传感器提示开关判断，判断逻辑如下
		 * 3.6.6新增提示开关设定
		 * 1，从提示开关表中获取“传感器提示开关”为关的设备id集合
		*/
		/******************获取传感器提示开关为关的设备id的集合begin******************/
		List<String> SensorPromptSwitchDown = this.tSensorAlarmDAO.getSensorPromtPSwitch();
		/******************获取传感器提示开关为关的设备id的集合end********************/
		float id = 0;
		for(Map<String,Object> oneAlarm:sourceList){
			/*对oneAlarm进行判断是否存在设备id的传感器提示开关为关的设备，如果存在则不做处理*/
			if(!SensorPromptSwitchDown.contains(MapGetter.getString(oneAlarm, "VehicleID"))){
				if(Float.parseFloat(MapGetter.getString(oneAlarm, "MsgAlm_ID"))>id){
					reMap = oneAlarm;
				}
				VehicleID = MapGetter.getString(oneAlarm, "VehicleID");
				MsgAlmC_SysA_ID = MapGetter.getString(oneAlarm, "MsgAlmC_SysA_ID");
				statFlag = VehicleID+"_"+MsgAlmC_SysA_ID;
				if(MapGetter.getString(oneAlarm,"MsgAlmC_IsAlarm").equals("true")){//报警
					if(this.promptList.contains(statFlag)){
						//已存在处于报警中状态的数据，不处理。
					}else{
						this.promptList.add(statFlag);
						if(MsgAlmC_SysA_ID.equals("17")){//温度
							if(this.SMSTemp){//发送短信
								userList = this.smsInfoDAO.getSMSUsers("SMSAS_SMSTempAlarm",MapGetter.getString(oneAlarm, "DBCode"), VehicleID);
								userSMS = this.getSMSUserOfSensorAlarm(oneAlarm,userList,1);
								this.tSensorAlarmDAO.getInsertPromptSQL(this.insertPrompt,this.paramPrompt,oneAlarm,17,userSMS);
							}else{//不发送短信
								this.tSensorAlarmDAO.getInsertPromptSQL(this.insertPrompt,this.paramPrompt,oneAlarm,17,null);
							}
						}else if(MsgAlmC_SysA_ID.equals("18")){
							if(this.SMSSmoke){//发送短信
								userList = this.smsInfoDAO.getSMSUsers("SMSAS_SMSSmokeAlarm",MapGetter.getString(oneAlarm, "DBCode"), VehicleID);
								userSMS = this.getSMSUserOfSensorAlarm(oneAlarm,userList,3);
								this.tSensorAlarmDAO.getInsertPromptSQL(this.insertPrompt,this.paramPrompt,oneAlarm,18,userSMS);
							}else{//不发送短信
								this.tSensorAlarmDAO.getInsertPromptSQL(this.insertPrompt,this.paramPrompt,oneAlarm,18,null);
							}
						}else{
							// 其他类型的报警不处理
						}
					}
				}else if(MapGetter.getString(oneAlarm,"MsgAlmC_IsAlarm").equals("false")){//解除
					if(this.promptList.contains(statFlag)){//必须有对应的报警信息才可解除。
						this.promptList.remove(statFlag);
						if(MsgAlmC_SysA_ID.equals("17")){//温度
							if(this.SMSTempRem){//发送短信
								userList = this.smsInfoDAO.getSMSUsers("SMSAS_SMSTempRels",MapGetter.getString(oneAlarm, "DBCode"), VehicleID);
								userSMS = this.getSMSUserOfSensorAlarm(oneAlarm,userList,2);
								this.tSensorAlarmDAO.getUpdatePromptSQL(this.insertPrompt,this.paramPrompt,oneAlarm,17,userSMS);
							}else{//不发送短信
								this.tSensorAlarmDAO.getUpdatePromptSQL(this.insertPrompt,this.paramPrompt,oneAlarm,17,null);
							}
						}else if(MsgAlmC_SysA_ID.equals("18")){//烟度
							if(this.SMSSmokeRem){//发送短信
								userList = this.smsInfoDAO.getSMSUsers("SMSAS_SMSSmokeRels",MapGetter.getString(oneAlarm, "DBCode"), VehicleID);
								userSMS = this.getSMSUserOfSensorAlarm(oneAlarm,userList,4);
								this.tSensorAlarmDAO.getUpdatePromptSQL(this.insertPrompt,this.paramPrompt,oneAlarm,18,userSMS);
							}else{//不发送短信
								this.tSensorAlarmDAO.getUpdatePromptSQL(this.insertPrompt,this.paramPrompt,oneAlarm,18,null);
							}
						}else{
							//其他报警类型不处理。
						}
					}else{
						//没有对应的报警中的报警信息什么也不做
					}
				}else{
					//无状态，不处理
				}
			}
		}
		return reMap;
	}

	/**
	 * 将提示表中的报警中的 传感器报警信息，拼成List<String> ,设备ID_17 （ 温度）,设备ID_18（ 烟度）,
	 **/
	private void getAlarmStateOfPrompt(
			List<Map<String, Object>> promptOfSensorAlarm) {
		//提示表中的存在报警中的 传感器报警信息
		this.promptList  = new ArrayList<String>();
		if(null!= promptOfSensorAlarm&&!promptOfSensorAlarm.isEmpty()){
			for(Map<String,Object> onePrompt:promptOfSensorAlarm){
				this.promptList.add(MapGetter.getString(onePrompt, "MsgP_VclID")+"_"+MapGetter.getString(onePrompt, "Msgp_SecTypeID"));
			}
		}
	}
	/**
	 * 调用拼接 短信发送方法，并 获取发送人、
	 * @param int type 1:温度报警；2：温度报警解除；3：烟度报警；4：烟度报警解除
	 **/
	private String getSMSUserOfSensorAlarm(Map<String, Object> oneAlarm,
			List<Map<String, Object>> userList,int type) {
		String reStr = "";
		String VehicleID = MapGetter.getString(oneAlarm, "VehicleID");
		//报警项目ID
		String ItemID = MapGetter.getString(oneAlarm, "MsgAlmC_SysA_ID");
		String MessageTime = MapGetter.getString(oneAlarm, "MsgAlm_MsgTime");
		String MsgID = MapGetter.getString(oneAlarm, "MsgAlm_ID");
		String MsgCID = MapGetter.getString(oneAlarm, "MsgAlmC_ID");
		String MsgAlmC_IsAlarm = MapGetter.getString(oneAlarm, "MsgAlmC_IsAlarm"); 
		StringBuffer strBuf = new StringBuffer();
		strBuf.append("select count(*) as cnt from SMS_SendRecord as sra inner join CTY_Egn_B.dbo.Msg_Alarm_Content as mac on sra.SSR_MsgCID=mac.MsgAlmC_ID ");
		if(StringUtil.isValid(MsgAlmC_IsAlarm)&&MsgAlmC_IsAlarm.equals("true")){
			strBuf.append(" and MsgAlmC_IsAlarm = 1 ");
		}else{
			strBuf.append(" and MsgAlmC_IsAlarm = 0 ");
		}
		strBuf.append("inner join CTY_Egn_B.dbo.Msg_Alarm as ma on mac.MsgAlmC_MsgAlm_ID = ma.MsgAlm_ID and ma.MsgAlm_Vcl_ID="+VehicleID
				+"inner join CTY_Egn_B.dbo.Sys_Alarm as sa on sa.SysA_ID=mac.MsgAlmC_SysA_ID and sa.SysA_ID="+ItemID+"  where 1=1 ");
		
		int configID = this.getSMSConfigID(type);
		//判断半小时内与本条设备ID、报警项目相同的报警信息是否发送过，若发送过则不发送，反之，发送。
		if(!smsInfoDAO.assTimeIsOccured(String.valueOf(configID),strBuf.toString())){//未发送
			//非工作时间是否发送
			if(!smsInfoDAO.nonWorkIsOccured(String.valueOf(configID),"ma.MsgAlm_MsgTime", MessageTime,strBuf.toString())){
				String SMSContent = this.getSMSContentOfSensorAlarm(oneAlarm,type); 
				Map<String, Object> SMSMap = new HashMap<String, Object>();
				SMSMap.put("SMSCfgType", configID);
				SMSMap.put("DBName", "B");
				SMSMap.put("TabName", "Msg_Alarm");
				SMSMap.put("PromptType", 14);
				SMSMap.put("CreateType", 1);
				SMSMap.put("SMSContent", SMSContent);
				SMSMap.put("DBCode", MapGetter.getString(oneAlarm, "DBCode"));
				SMSMap.put("MsgID", MsgID);
				SMSMap.put("MsgCID", MsgCID);
				//拼接短信发送SQL
				smsInfoDAO.promptSMSInfo(this.insertSMS,this.paramSMS,SMSMap,userList);
				reStr = SMSMap.remove("smsuser").toString();
			}else{//非工作时间是发送过
				
			}
		}else{//半小时内发送过
			
		}
		return reStr;
	}
	/**
	 * 获取传感器报警的短信内容
	 **/
	private String getSMSContentOfSensorAlarm(Map<String, Object> oneAlarm,int type) {
		String reStr = "";
		//获得设备号
		String VehicleNumber = MapGetter.getString(oneAlarm, "VehicleNumber");
		
		String time = DateList.getFormatDate(MapGetter.getString(oneAlarm, "MsgAlm_MsgTime"), 10);
		
		String dateValue = "";
		if(MapGetter.getString(oneAlarm,"MsgAlmC_SysA_ID").equals("17")){
			dateValue = StringUtil.isValid(MapGetter.getString(oneAlarm, "MsgAlmC_Value"))?String.valueOf(NumberFormat.round((Double.parseDouble(MapGetter.getString(oneAlarm, "MsgAlmC_Value"))),1)):"";
		}else{
			//报警项目名称
			dateValue = "烟度异常";
		}

		switch(type){
		case 1:
			reStr = SMSContentCfg.SMSCCfgServiceTemp.replace("X_VclNum", VehicleNumber).replace("X_Time", time).replace("X_temp", dateValue);
			break;
		case 2:
			reStr = SMSContentCfg.SMSCCfgServiceSMTempRem.replace("X_VclNum", VehicleNumber).replace("X_Time", time).replace("X_temp", dateValue);
			break;
		case 3:
			reStr = SMSContentCfg.SMSCCfgServiceSmoke.replace("X_VclNum", VehicleNumber).replace("X_Time", time);
			break;
		case 4:
			reStr = SMSContentCfg.SMSCCfgServiceSmokeRem.replace("X_VclNum", VehicleNumber).replace("X_Time", time);
			break;
		default:
			break;
		}
		return reStr;
	}
	/**
	 * 获取传感器报警的短信配置 的 typeID  即SMS_Config。SC_Type
	 **/
	private int getSMSConfigID(int type) {
		int reStr = 0;
		switch(type){
		case 1:
			reStr = 14;  
			break;
		case 2:
			reStr = 15;
			break;
		case 3:
			reStr = 12;
			break;
		case 4:
			reStr = 13;
			break;
		default:
			break;
		}
		return reStr;
	}
	
}